<script>
// 素材-地图
import config from 'config';

//应用模板分类代码
const MAP_TEMPLATE_CODE = '95100';

export default {
  name: 'MaterialMap',
  data() {
    return {
      keyword: '', //查询关键字
      totalCount: 0, //总记录数
      pagedData: [], //列表分页数据
      pageSize: 10, //分页大小
      formData: {}, //表单Model
      //表单验证规则
      ruleValidate: {
        name: [{ required: true, message: ' ', trigger: 'blur' }],
        uri: [{ required: true, message: ' ', trigger: 'blur' }],
        file: [{ required: true, message: ' ', trigger: 'blur' }],
      },
      modalOpened: false, //新增对话框是否打开
      editMode: -1, //编辑模式，0:新增，1：编辑
      editId: null, //编辑ID
      uploadService: `${config.portal.basicUrl}/data/fileupload/staticserver`, //上传服务地址
      compomentList: [
        {
          name: 'mapItem',
          label: '基础地图',
        },
        {
          name: 'overlapMap',
          label: '双屏对比分析',
        },
      ],
    };
  },
  computed: {
    //对话框标题
    modalTitle() {
      return this.editMode == 0 ? '新增地图模板' : '编辑地图模板';
    },
  },
  async beforeMount() {
    this.doQuery();
  },
  methods: {
    //获取分页数据
    async doQuery() {
      const response = await this.getPagedData(1);
      this.totalCount = response.data.pageInfo.totalCount;
    },
    //获取分页信息，并加载第一页
    async getPagedData(pageIndex) {
      const response = await api.datav.findAppList({
        objCondition: {
          name: this.keyword,
          typeId: MAP_TEMPLATE_CODE,
        },
        orderby: 'createTime_desc',
        pageIndex: pageIndex,
        pageSize: this.pageSize,
      });
      this.pagedData = response.data.dataSource;
      return response;
    },
    //上传图片成功
    uploadSuccess(e) {
      this.formData.thumbUri = e.data;
    },
    //上传图片失败
    uploadError(e) {
      this.$Message.error('上传图片失败!');
    },
    //校验表单数据
    validateData() {
      this.$refs.templateForm.validate();
      if (!this.formData.name) {
        this.$Message.warning('模板名称为必填项！');
        return false;
      }
      if (!this.formData.uri) {
        this.$Message.warning('模板地址为必填项！');
        return false;
      }
      if (!this.formData.thumbUri) {
        this.$Message.warning('未上传模板封面！');
        return false;
      }
      return true;
    },
    //新增应用模板
    addAppTemplate() {
      this.formData = {};
      this.$refs.templateForm.resetFields();
      this.editMode = 0;
      this.modalOpened = true;
    },
    //编辑应用模板
    editAppTemplate(item) {
      this.formData.name = item.name;
      this.formData.uri = item.path;
      this.formData.thumbUri = item.thumbUri;
      this.formData.description = item.description;
      this.editMode = 1;
      this.editId = item.id;
      this.modalOpened = true;
    },
    //删除应用模板
    deleteAppTemplate(dataId) {
      this.$Modal.confirm({
        title: '删除提示',
        content: '数据删除后不可恢复，您确定要删除吗？',
        onOk: () => {
          api.datav.deleteApp({ id: dataId }).then(e => {
            this.doQuery();
            this.$Message.success('数据删除成功!');
          });
        },
      });
    },
    //浏览应用模板
    viewAppTemplate() {},
    //保存编辑的应用模板
    async saveEditMapTemplate() {
      let appData = {
        appExEntity: {
          path: this.formData.uri,
          info: '',
          data: '',
        },
        infoEntity: {
          id: this.editId,
          name: this.formData.name,
          alias: this.formData.name,
          thumbUri: this.formData.thumbUri,
          description: this.formData.description,
        },
      };
      return await api.datav.updateApp(appData);
    },
    //保存应用模板
    async saveAppTemplate() {
      if (!this.validateData()) return;
      const saveFunc = this.editMode == 0 ? this.saveAddMapTemplate : this.saveEditMapTemplate;
      const response = await saveFunc();
      this.$Message.success('模板保存成功!');
      this.modalOpened = false;
      this.doQuery();
    },
    //保存新增的应用模板
    async saveAddMapTemplate() {
      const userInfo = this.$store.state.user.info; //用户信息
      let appData = {
        appExEntity: {
          path: this.formData.uri,
          info: '',
          data: '',
        },
        infoEntity: {
          userId: userInfo.id,
          orgId: userInfo.orgid,
          name: this.formData.name,
          alias: this.formData.name,
          typeId: MAP_TEMPLATE_CODE,
          thumbUri: this.formData.thumbUri,
          description: this.formData.description,
        },
      };
      return await api.datav.addApp(appData);
    },
  },
};
</script>

<template>
  <div class="app-template-wrapper">
    <div class="app-template-header">
      <Input
        v-model="keyword"
        placeholder="输入地图模板名称按Enter键搜索..."
        icon="search"
        @keyup.native.enter="doQuery()"></Input>
      <Button
        type="primary"
        @click="addAppTemplate">
        <Icon type="plus"></Icon>
        新增
      </Button>
      <Modal
        v-model="modalOpened"
        :mask-closable="false"
        width="400"
        class="add-template-modal">
        <Form
          ref="templateForm"
          :model="formData"
          :rules="ruleValidate"
          :label-width="90">
          <Form-item
            class="formItem"
            label="模板名称："
            prop="name">
            <Input
              v-model="formData.name"
              placeholder="请输入名称" />
          </Form-item>
          <Form-item
            class="formItem"
            label="模板类型："
            prop="uri">
            <Select
              v-model="formData.uri"
              style="width:200px">
              <Option
                v-for="(item) in compomentList"
                :value="item.name"
                :key="item.name">{{ item.label }}</Option>
            </Select>
          </Form-item>
          <Form-item
            class="formItem"
            label="模板封面："
            prop="file">
            <Upload
              :show-upload-list="false"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :format="['jpg','jpeg','png']"
              :action="uploadService">
              <Button
                type="ghost"
                icon="ios-cloud-upload-outline">上传封面</Button>
            </Upload>
          </Form-item>
          <Form-item
            class="formItem"
            label="模板描述："
            prop="description"
            style="height: 60px;">
            <Input
              v-model="formData.description"
              type="textarea"
              placeholder="描述" />
          </Form-item>
        </Form>
        <div slot="header">
          <div>{{ modalTitle }}</div>
        </div>
        <div slot="footer">
          <Button
            type="text"
            @click="modalOpened=false">取消</Button>
          <Button
            type="primary"
            @click="saveAppTemplate">确定</Button>
        </div>
      </Modal>
    </div>
    <div class="app-template-content">
      <Row
        type="flex"
        justify="start">
        <Card
          v-for="item in pagedData"
          :key="item.id"
          class="template-card"
          @click.native="viewAppTemplate(item)">
          <div class="template-card-cover">
            <div
              :style="{backgroundImage:'url('+item.thumbUri+')'}"
              class="card-background"></div>
            <div class="card-overlay">
              <Icon
                type="search"
                title="浏览" />
              <Icon
                type="edit"
                title="编辑"
                @click.native.stop="editAppTemplate(item)" />
              <Icon
                type="close-circled"
                title="删除"
                @click.native.stop="deleteAppTemplate(item.id)" />
            </div>
          </div>
          <div class="template-card-info">
            <p>{{ item.name }}</p>
            <div>
              <span class="card-info-person">
                <Icon
                  type="person"></Icon>
              </span>
              <span>管理员</span>
              <span class="card-info-time">
                {{ item.createTime|tickToDateString }}
              </span>
            </div>
          </div>
        </Card>
      </Row>
      <Page
        :total="totalCount"
        :page-size="pageSize"
        @on-change="getPagedData">
      </Page>
    </div>
  </div>
</template>
<style lang="less">
.app-template-wrapper {
  background-color: #ffffff;
  height: 100%;
  position: relative;
}

.app-template-header {
  height: 50px;
  line-height: 50px;
  background-color: #f2f2f2;
  padding: 0 15px;
  .k-input-wrapper {
    width: 250px;
    margin-right: 5px;
  }
}

.app-template-content {
  position: absolute;
  top: 50px;
  right: 0;
  bottom: 50px;
  left: 0;
  overflow-y: auto;
  .k-row-flex {
    margin: 20px 0 20px 15px;
  }
  .k-page {
    margin: 15px 40px 0 0;
    text-align: right;
  }
}

.add-template-modal {
  .k-modal-body {
    padding-bottom: 0;
  }
}
</style>
